<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

class InformSendController extends Controller
{

    public function index(Request $request, $informId)
    {
        $input = $request->all();

        //通知时间
        $sendTime = date("Y-m-d H:i:s");
        
        //获取通知人数
        $informUserCount = DB::table("im_inform_user")->where("inform_id",$informId)->count();
        if($informUserCount == 0)
            return $this::jsonResponse(true,[],"InformSendNoUser");

        //更新通知发送状态
        $informSendData = [
            "is_sent"           => true,
            "send_time"         => $sendTime,
            "send_count"        => $informUserCount
        ];

        $informSendResult = DB::table("im_inform")
            ->where("id",$informId)
            ->where("is_sent",false)
            ->where("is_deleted",false)
            ->update($informSendData);
    	
        if(!$informSendResult)
            return $this::jsonResponse(true,[],"InformSended");

        //触发通知方式（触发类型1，几秒后）
        DB::update("UPDATE im_inform_method 
            SET could_send = true, could_send_time =  date_add('$sendTime',interval trigger_value second)
            WHERE trigger_type = 1 AND inform_id = $informId;");

        //创建通知集与用户的关联
        $informUserResult = DB::table("im_inform_user")
            ->select("user_id")
            ->where("inform_id",$informId)
            ->get();
        $setUserData = [];
        $setId = DB::table("im_inform")->where("id",$informId)->value("set_id");
        $userIds = [];
        foreach ($informUserResult as $key => $value) {
            $setUserData[] = [
                "set_id"    => $setId,
                "inform_id" => $informId,
                "user_id"   => $value->user_id,
            ];
            $userIds[] =  $value->user_id;
        }
        DB::table("im_set_user")
            ->where("set_id",$setId)
            ->whereIn("user_id",$userIds)
            ->update(["is_latest"=>false]);

        DB::table("im_set_user")->insert($setUserData);

        //及时通知
        //$this->api->get("/message/check");

        return $this::jsonResponse(false,$sendTime);
	}
}